#include <my_head.h>

typedef struct _Msg{
    int id;
    char gender;
    short score;
    char name[16];
}msg_t;

int main(int argc, const char *argv[]){
    int fd = 0;
    // 打开文件
    if(-1 == (fd = open("hello.txt", O_RDWR|O_CREAT|O_TRUNC, 0664)))
        ERR_LOG("open error");
    // 1.写入整数
        int num1 = 1234;
        write(fd, &num1, 4);
        lseek(fd, 0, SEEK_SET); // 重置光标到文件开头
        int num2 = 0;
        read(fd, &num2, 4);
        printf("num2 = %d\n", num2); // 1234
    // 2.写入字符串
        lseek(fd, 0, SEEK_SET); // 重置光标到文件开头
        char buff1[20] = "hello world";
        write(fd, buff1, 11); // 不要草率的写sizeof或者strlen !!! 
        lseek(fd, 0, SEEK_SET); // 重置光标到文件开头
        char buff2[20] = {0};
        read(fd, buff2, sizeof(buff2));
        printf("buff2 = [%s]\n", buff2); // hello world
    // 3.写入结构体
        lseek(fd, 0, SEEK_SET); // 重置光标到文件开头
        msg_t msg1 = {1001, 'M', 97, "zhangsan"};
        write(fd, &msg1, sizeof(msg1));
        lseek(fd, 0, SEEK_SET); // 重置光标到文件开头
        msg_t msg2;
        read(fd, &msg2, sizeof(msg2));
        printf("%d %c %d %s\n", msg2.id, msg2.gender, msg2.score, msg2.name); // 1001 'M' 97 zhangsan
    // 关闭文件
    close(fd);
    return 0;
}